package com.rex.saas.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.rex.saas.bean.*;
import com.rex.saas.bean.request.CategoryAddRequest;
import com.rex.saas.bean.response.AssetResponse;
import com.rex.saas.config.CustomConfig;
import com.rex.saas.constants.ApiConstant;
import com.rex.saas.constants.Constants;
import com.rex.saas.enums.StatusEnum;
import com.rex.saas.utils.JsonUtils;
import com.rex.saas.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.*;

/**
 * @ClassName RexolarApiClient
 * @Description:
 * @Author: zhusiyu
 * @CreateDate: 2024/12/11 19:41	//创建时间
 */
@Slf4j
@Service
public class RexolarApiClient {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CustomConfig customConfig;

    @Autowired
    private Cache<String, String> userTokenCache;

    /**
     * 获取Token
     * fixedRate: 单位ms
     */
    public Map authLogin(String username, String password) {
        HttpHeaders headers = new HttpHeaders();
        // 构建请求体的 JSON 字符串
        HashMap<String, String> requestBodyMap = new HashMap<>();
        requestBodyMap.put("username", username);
        requestBodyMap.put("password", password);
        String requestBody = JSON.toJSONString(requestBodyMap);

        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        String url = customConfig.getHttpApi() + ApiConstant.AUTH_LOGIN;
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );
            HttpStatus statusCode = responseEntity.getStatusCode();
            Map<String, Object> responseBody = responseEntity.getBody();
//            JwtTokenCache.put(email, responseBody);
            if (!statusCode.is2xxSuccessful()) {
                log.error("## authLogin 执行结束： url:{},requestBodyMap：{},  statusCode={}, 结果={}", url, requestBodyMap, statusCode, responseEntity);
                return null;
            }
            // 返回 JSON 格式的响应体
            return responseBody;
        } catch (HttpClientErrorException e) {
            // 捕获 HTTP 401 异常
            if (HttpStatus.UNAUTHORIZED.equals(e.getStatusCode())) {
                // 处理身份验证失败的情况
                log.error("Authentication failed. Invalid email or password. ", e);
            } else {
                // 处理其他 HTTP 异常
                log.error("HTTP request failed. Status code: {}", e.getStatusCode(), e);
            }
//            JwtTokenCache.put(email, null);
            return null;
        }catch (Exception e){
            log.error("authLogin Exception, ", e);
            return null;
        }
    }

    /**
     * 获取Token
     * fixedRate: 单位ms
     */
    public Boolean authLogout(String token) {
        HttpHeaders headers = new HttpHeaders();
        // 构建请求体的 JSON 字符串
        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        String url = customConfig.getHttpApi() + ApiConstant.AUTH_LOGOUT;
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );
            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## authLogout 执行结束： url:{},  statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }

        }catch (Exception e){
            log.error("authLogout Exception, ", e);
            throw e;
        }
        return true;
    }

    private Map<String, Object> postMethod(String url, String data, String token){
        HttpHeaders headers = new HttpHeaders();
        Map<String, Object> responseBody = new HashMap<>();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        HttpEntity<String> entity = new HttpEntity<>(data, headers);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );
            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## postMethod 执行结束： url:{},  statusCode={}, 结果={}, data:{}", url, statusCode, responseEntity, data);
                responseBody.put("result", false);
                return responseBody;
            }
            if(responseEntity.getBody()!=null){
                responseBody.putAll(responseEntity.getBody());
            }
            responseBody.put("result", true);
            return responseBody;
        } catch (HttpClientErrorException e) {
            log.error("postMethod HttpClientErrorException failed. url:{}, data:{}", url, data, e);
            responseBody.put("result", false);
            return responseBody;
        }
    }

    private Map<String, Object> getMethod(String url, String token){
        HttpHeaders headers = new HttpHeaders();
        Map<String, Object> responseBody = new HashMap<>();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );
            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getMethod 执行结束： url:{},  statusCode={}, 结果={}", url, statusCode, responseEntity);
                responseBody.put("result", false);
                return responseBody;
            }
            responseBody = responseEntity.getBody();
            responseBody.put("result", true);
            return responseBody;
        } catch (HttpClientErrorException e) {
            log.error("getMethod HttpClientErrorException failed. url:{}", url, e);
            throw e;
        }
    }


    /**
     * 更新设备的属性数据
     *
     * @param deviceId
     * @param scope
     * @param data
     * @return
     */
    public boolean updateDeviceAttributes(String deviceId, String scope, String data, String token) {
        //校验数据是否合规
        if (!JsonUtils.isJson(data) || StringUtils.isBlank(deviceId) || StringUtils.isBlank(scope)) {
            return false;
        }
        String url = customConfig.getHttpApi() + ApiConstant.UPDATE_DEVICE_ATTRIBUTES.replace("{deviceId}", deviceId).replace("{scope}", scope);
        Map<String, Object> responseMap = postMethod(url, data, token);
        return responseMap.get("result") != null && (Boolean) responseMap.get("result");
//
//        HttpHeaders headers = new HttpHeaders();
//
//        headers.add("Content-Type", "application/json");
//        headers.add("accept", "application/json");
//        headers.add("X-Authorization", "Bearer " + token);
//
//        HttpEntity<String> entity = new HttpEntity<>(data, headers);
//
//        //构建请求链接
//        String url = customConfig.getHttpApi() + ApiConstant.UPDATE_DEVICE_ATTRIBUTES.replace("{deviceId}", deviceId).replace("{scope}", scope);
//        try {
//            // 期望 JSON 响应
//            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
//                    url,
//                    HttpMethod.POST,
//                    entity,
//                    new ParameterizedTypeReference<Map<String, Object>>() {
//                    }
//            );
//
//            HttpStatus statusCode = responseEntity.getStatusCode();
//            if (!statusCode.is2xxSuccessful()) {
//                log.error("## updateDeviceAttributes 执行结束： url:{},  statusCode={}, 结果={}", url, statusCode, responseEntity);
//                return false;
//            }
//            Map<String, Object> responseBody = responseEntity.getBody();
//            log.warn("## updateDeviceAttributes url:{}, 执行结束： statusCode={}, 结果={}", url, statusCode, responseBody);
//
//        } catch (HttpClientErrorException e) {
//            log.error(e.getMessage(), e);
//            // 捕获 HTTP 401 异常
//            if (HttpStatus.UNAUTHORIZED.equals(e.getStatusCode())) {
//                // 处理身份验证失败的情况
//                log.error("Authentication failed. Invalid email or password.", e);
//            } else {
//                // 处理其他 HTTP 异常
//                log.error("HTTP request failed.", e);
//            }
//            return false;
//        }

//        return true;

    }


    /**
     * 更新设备的遥测数据
     *
     * @param deviceId
     * @param data
     * @return
     */
    public boolean updateDeviceTelemetry(String deviceId, String data,String token) {
        //校验数据是否合规
        if (!JsonUtils.isJson(data) || StringUtils.isBlank(deviceId)) {
            return false;
        }
        String url = customConfig.getHttpApi() + ApiConstant.UPDATE_DEVICE_TELEMETRY.replace("{entityId}", deviceId).replace("{entityType}", "DEVICE");
        Map<String, Object> responseMap = postMethod(url, data, token);
        return responseMap.get("result") != null && (Boolean) responseMap.get("result");
//        HttpHeaders headers = new HttpHeaders();
//
//        headers.add("Content-Type", "application/json");
//        headers.add("accept", "application/json");
//        headers.add("X-Authorization", "Bearer " + token);
//
//        HttpEntity<String> entity = new HttpEntity<>(data, headers);
//
//        //构建请求链接
//        String url = customConfig.getHttpApi() + ApiConstant.UPDATE_DEVICE_TELEMETRY.replace("{entityId}", deviceId).replace("{entityType}", "DEVICE");
//        try {
//            // 期望 JSON 响应
//            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
//                    url,
//                    HttpMethod.POST,
//                    entity,
//                    new ParameterizedTypeReference<Map<String, Object>>() {
//                    }
//            );
//
//            HttpStatus statusCode = responseEntity.getStatusCode();
//            if (!statusCode.is2xxSuccessful()) {
//                log.error("## updateDeviceTelemetry 执行结束： url:{},  statusCode={}, 结果={}", url, statusCode, responseEntity);
//                return false;
//            }
//            Map<String, Object> responseBody = responseEntity.getBody();
//
//            log.warn("## updateDeviceTelemetry url:{}, 执行结束： statusCode={}, 结果={}", url, statusCode, responseBody);
//
//        } catch (Exception e) {
//            log.error("updateDeviceTelemetry Exception, ", e);
//            throw e;
//        }
//
//        return true;
    }


    /**
     * 获取设备属性数据
     *
     * @param deviceId
     * @param token
     * @return
     */
    public List<DeviceAttributesData> getDeviceAttributes(String deviceId, String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceId)) {
            return null;
        }

        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_ATTRIBUTES.replace("{deviceId}", deviceId);
        try {
            // 期望 JSON 响应
            ResponseEntity<List<DeviceAttributesData>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<List<DeviceAttributesData>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            List<DeviceAttributesData> responseBody = responseEntity.getBody();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceAttributes 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }

            return responseBody;
        }catch (HttpClientErrorException ex){
            if (ex.getStatusCode() == HttpStatus.NOT_FOUND){
                return null;
            }
            log.error("## getDeviceAttributes HttpClientErrorException： url:{}", url, ex);
        } catch (Exception e){
            log.error("getDeviceAttributes Exception ",e);
            throw e;
        }
        return null;
    }

    /**
     * 获取设备历史遥测数据
     *
     * @param deviceId
     * @param token
     * @return
     */
    public Map<String, Object> getDeviceTimeSeries(String deviceId, String token, String[] keys, long startTime, long endTime, int limit, boolean desc,Long interval,String agg,Boolean useStrictDataTypes) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceId) || keys.length == 0) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        Map<String, Object> result = null;
        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_TIME_SERIES.replace("{deviceId}", deviceId);
        // 构建请求参数
        String keysStr = String.join(",", keys);
        String orderBy = desc ? "DESC" : "ASC";

        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("keys", keysStr)
                .queryParam("startTs", startTime)
                .queryParam("endTs", endTime)
                .queryParam("orderBy", orderBy);
        if (limit > 0){
            builder.queryParam("limit", limit);
        }
        if (interval != null){
            builder.queryParam("interval", interval);
        }
        if (agg != null){
            builder.queryParam("agg", agg);
        }
        if (useStrictDataTypes != null){
            builder.queryParam("useStrictDataTypes", useStrictDataTypes);
        }
        url = builder.toUriString();

        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceTimeSeries 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            return responseEntity.getBody();
        } catch (HttpClientErrorException ex){
            log.error("## getDeviceTimeSeries HttpClientErrorException url:{} ", url, ex);
            if (ex.getStatusCode() == HttpStatus.NOT_FOUND){
                return result;
            }
        } catch (Exception e) {
            log.error("getDeviceTimeSeries Exception , url:{}",url, e);
            return result;
        }
        return result;
    }

    /**
     * 获取租户下用户信息
     *
     * @param tenantId
     * @param token
     * @return
     */
    public List<UserBasicData> getTenantUsers(String tenantId, String token) {
        List<UserBasicData> dataList = new ArrayList<>();
        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANT_USERS.replace("{tenantId}", tenantId);
                UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 1000)
                .queryParam("sortProperty", "createdTime")
                .queryParam("sortOrder", "DESC");
        url = builder.toUriString();
        Map<String, Object> responseBody = getMethod(url,token);
        if(responseBody.get("data")!=null){
            List<Map> data = (List<Map>) responseBody.get("data");
            for(Map item: data){
                UserBasicData userBasicData = new UserBasicData();
                Object id = ((Map)item.get("id")).get("id");
                Object phone = item.get("phone");
                Object name = item.get("name");
                Object type = item.get("email");
                Object authority = item.get("authority");
                userBasicData.setId((String) id);
                userBasicData.setTenantId(tenantId);
                userBasicData.setName((String) name);
                userBasicData.setEmail((String) type);
                userBasicData.setAuthority((String) authority);
                userBasicData.setPhone((String) phone);
                dataList.add(userBasicData);
            }
        }
        return  dataList;
//        HttpHeaders headers = new HttpHeaders();
//
//        headers.add("Content-Type", "application/json");
//        headers.add("accept", "application/json");
//        headers.add("X-Authorization", "Bearer " + token);
//
//        HttpEntity<String> entity = new HttpEntity<>(null, headers);
//
//        //构建请求链接
//        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANT_USERS.replace("{tenantId}", tenantId);
//        // 构建请求参数
//        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
//                .queryParam("page", 0)
//                .queryParam("pageSize", 1000)
//                .queryParam("sortProperty", "createdTime")
//                .queryParam("sortOrder", "DESC");
//        url = builder.toUriString();
//
//        try {
//            // 期望 JSON 响应
//            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
//                    url,
//                    HttpMethod.GET,
//                    entity,
//                    new ParameterizedTypeReference<Map<String, Object>>() {
//                    }
//            );
//
//            HttpStatus statusCode = responseEntity.getStatusCode();
//            if (!statusCode.is2xxSuccessful()) {
//                log.error("## getTenantUsers 执行结束： url:{}, statusCode={}", url, statusCode);
//                return null;
//            }Map<String, Object> responseBody = responseEntity.getBody();
//            List<Map> data = (List<Map>) responseBody.get("data");
//            for(Map item: data){
//                UserBasicData userBasicData = new UserBasicData();
//                Object spaceInfoId = ((Map)item.get("spaceInfoId")).get("spaceInfoId");
//                Object phone = item.get("phone");
//                Object gwName = item.get("gwName");
//                Object type = item.get("email");
//                Object authority = item.get("authority");
//                userBasicData.setSpaceInfoId((String) spaceInfoId);
//                userBasicData.setTenantId(tenantId);
//                userBasicData.setGwName((String) gwName);
//                userBasicData.setEmail((String) type);
//                userBasicData.setAuthority((String) authority);
//                userBasicData.setPhone((String) phone);
//                dataList.add(userBasicData);
//            }
//            return  dataList;
//        } catch (HttpClientErrorException ex){
//            if (ex.getStatusCode() == HttpStatus.NOT_FOUND){
//                return dataList;
//            }
//            log.error("## getTenantUsers HttpClientErrorException , url:{}", url, ex);
//        } catch (Exception e) {
//            log.error("getTenantUsers Exception ",e);
//            throw e;
//        }
//        return dataList;
    }

    /**
     * 获取租户下用户信息
     *
     * @param customerId
     * @param token
     * @return
     */
    public List<UserBasicData> getCustomerUsers(String customerId, String token) {
        List<UserBasicData> dataList = new ArrayList<>();
        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_CUSTOMER_USERS.replace("{customerId}", customerId);
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
        .queryParam("page", 0)
        .queryParam("pageSize", 1000)
        .queryParam("sortProperty", "createdTime")
        .queryParam("sortOrder", "DESC");
        url = builder.toUriString();
        Map<String, Object> responseBody = getMethod(url,token);
        if(responseBody.get("data")!=null){
            List<Map> data = (List<Map>) responseBody.get("data");
            for(Map item: data){
                UserBasicData userBasicData = new UserBasicData();
                Object id = ((Map)item.get("id")).get("id");
                Object tenantId = ((Map)item.get("tenantId")).get("id");
                Object phone = item.get("phone");
                Object name = item.get("name");
                Object type = item.get("email");
                Object authority = item.get("authority");
                userBasicData.setId((String) id);
                userBasicData.setTenantId((String) tenantId);
                userBasicData.setName((String) name);
                userBasicData.setEmail((String) type);
                userBasicData.setAuthority((String) authority);
                userBasicData.setPhone((String) phone);
                dataList.add(userBasicData);
            }
        }
        return  dataList;
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Content-Type", "application/json");
//        headers.add("accept", "application/json");
//        headers.add("X-Authorization", "Bearer " + token);
//
//        HttpEntity<String> entity = new HttpEntity<>(null, headers);
//
//
//        // 构建请求参数
//        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
//                .queryParam("page", 0)
//                .queryParam("pageSize", 1000)
//                .queryParam("sortProperty", "createdTime")
//                .queryParam("sortOrder", "DESC");
//        url = builder.toUriString();
//
//        try {
//            // 期望 JSON 响应
//            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
//                    url,
//                    HttpMethod.GET,
//                    entity,
//                    new ParameterizedTypeReference<Map<String, Object>>() {
//                    }
//            );
//
//            HttpStatus statusCode = responseEntity.getStatusCode();
//            if (!statusCode.is2xxSuccessful()) {
//                log.error("## getCustomerUsers 执行结束： url:{}, statusCode={}", url, statusCode);
//                return null;
//            }Map<String, Object> responseBody = responseEntity.getBody();
//            List<Map> data = (List<Map>) responseBody.get("data");
//            for(Map item: data){
//                UserBasicData userBasicData = new UserBasicData();
//                Object spaceInfoId = ((Map)item.get("spaceInfoId")).get("spaceInfoId");
//                Object tenantId = ((Map)item.get("tenantId")).get("spaceInfoId");
//                Object phone = item.get("phone");
//                Object gwName = item.get("gwName");
//                Object type = item.get("email");
//                Object authority = item.get("authority");
//                userBasicData.setSpaceInfoId((String) spaceInfoId);
//                userBasicData.setTenantId((String) tenantId);
//                userBasicData.setGwName((String) gwName);
//                userBasicData.setEmail((String) type);
//                userBasicData.setAuthority((String) authority);
//                userBasicData.setPhone((String) phone);
//                dataList.add(userBasicData);
//            }
//            return  dataList;
//        } catch (HttpClientErrorException ex){
//            if (ex.getStatusCode() == HttpStatus.NOT_FOUND){
//                return dataList;
//            }
//            log.error("## getCustomerUsers 执行结束： url:{}, statusCode={}, 结果={}", url, ex.getStatusCode(), ex.getResponseBodyAsString());
//        } catch (Exception e) {
//            log.error("getCustomerUsers error:{}",e.getMessage());
//            throw e;
//        }
//        return dataList;
    }


    /**
     * 动态创建设备
     *
     * @param data
     * @param token
     * @return
     */
    public String dynamicCreateDevice(String data, String token) {
        //校验数据是否合规
        if (!JsonUtils.isJson(data) || StringUtils.isBlank(token)) {
            return "";
        }
        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.DYNAMIC_CREATE_DEVICE;

        Map<String, Object> responseBody = postMethod(url, data, token);
        if (responseBody.get("id") != null) {
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);
        }else {
            return "";
        }

//        HttpHeaders headers = new HttpHeaders();
//
//        headers.add("Content-Type", "application/json");
//        headers.add("accept", "application/json");
//        headers.add("X-Authorization", "Bearer " + token);
//
//        HttpEntity<String> entity = new HttpEntity<>(data, headers);
//
//
//        log.info("dynamicCreateDevice Url: " + url);
//        try {
//            // 期望 JSON 响应
//            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
//                    url,
//                    HttpMethod.POST,
//                    entity,
//                    new ParameterizedTypeReference<Map<String, Object>>() {
//                    }
//            );
//
//            HttpStatus statusCode = responseEntity.getStatusCode();
//            if(!statusCode.is2xxSuccessful()){
//                log.warn("## dynamicCreateDevice 执行结束： statusCode={}", statusCode);
//                return null;
//            }
//            Map<String, Object> responseBody = responseEntity.getBody();
//            Map idMap = (Map)responseBody.get("spaceInfoId");
//            Object spaceInfoId = idMap.get("spaceInfoId");
//            return String.valueOf(spaceInfoId);
//        } catch (Exception e) {
//            log.error("dynamicCreateDevice error:{}",e.getMessage());
//            throw e;
//        }

    }


    /**
     * 获取设备最新的遥测数据
     *
     * @param deviceId
     * @param token
     * @return
     */
    public Map<String, List<DeviceTimeSeries>> getDeviceTimeSeriesLatest(String deviceId, String token, String[] keys,Boolean useStrictDataTypes) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceId)) {
            return null;
        }
        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_TIME_SERIES_LATEST.replace("{deviceId}", deviceId);

        Map<String, List<DeviceTimeSeries>> result = new HashMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        // 构建请求参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        if (keys.length >0){
            String keysStr = String.join(",", keys);
            builder.queryParam("keys", keysStr);
        }

        if (useStrictDataTypes != null){
            builder.queryParam("useStrictDataTypes", useStrictDataTypes);
        }
        url = builder.toUriString();

        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, List<DeviceTimeSeries>>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, List<DeviceTimeSeries>>>() {
                    }
            );
            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceTimeSeriesLatest 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return result;
            }
            return responseEntity.getBody();

        } catch (HttpClientErrorException ex){
            log.error("## getDeviceTimeSeriesLatest 执行结束： url:{}, statusCode={}", url, ex.getStatusCode());
            if (ex.getStatusCode() == HttpStatus.NOT_FOUND){
                return result;
            }
        }catch (Exception e) {
            log.error("getDeviceTimeSeriesLatest error:{}",e.getMessage());
            throw e;
        }
        return result;
    }

    /**
     * 删除资产
     *
     * @param assetId
     * @return
     */
    public boolean deleteAsset(String assetId,String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(assetId)) {
            return false;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.OPT_ASSET.replace("{assetId}", assetId);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            Map<String, Object> responseBody = responseEntity.getBody();
            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## deleteAsset 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }

        } catch (Exception e) {
            log.error("deleteAsset error:{}",e.getMessage());
            return false;
        }

        return true;

    }

    /**
     * 删除设备
     *
     * @param deviceId
     * @return
     */
    public boolean deleteDevice(String deviceId,String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(deviceId)) {
            return false;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.DELETE_DEVICE.replace("{deviceId}", deviceId);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            Map<String, Object> responseBody = responseEntity.getBody();
            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## deleteDevice 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }

        } catch (Exception e) {
            log.error("deleteDevice error:{}",e.getMessage());
            throw e;
        }

        return true;

    }



    /**
     * 获取设备某个属性数据
     *
     * @param deviceId
     * @param token
     * @param keys
     * @return
     */
    public Map<String,Object> getDeviceAttributes(String deviceId, String token, String[] keys) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceId)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_ATTRIBUTES.replace("{deviceId}", deviceId);
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        if (keys.length >0){
            String keysStr = String.join(",", keys);
            builder.queryParam("keys", keysStr);
        }
        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity<List<DeviceAttributesData>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<List<DeviceAttributesData>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            List<DeviceAttributesData> responseBody = responseEntity.getBody();
            LinkedHashMap<String, Object> result = new LinkedHashMap<>();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceAttributes 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            if (responseBody.size() > 0) {
                for (DeviceAttributesData item : responseBody) {
                    result.put(item.getKey(), item.getValue());
                }
                return result;
            }

            return null;
        }catch (HttpClientErrorException ex){
            if (ex.getStatusCode() == HttpStatus.NOT_FOUND){
                return null;
            }
            log.error("## getDeviceAttributes 执行结束： url:{}", url, ex);

        } catch (Exception e) {
            log.error("getDeviceAttributes Exception ",e);
            throw e;
        }
        return null;
    }

    /**
     * 获取设备id数据
     * 通过设备名称获取
     *
     * @param pageNo
     * @param pageSize
     * @param token
     * @return
     */
    public Page<DeviceBasicData> getDeviceListPage(Integer pageNo, Integer pageSize, String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(token)) {
            return null;
        }

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANT_DEVICES;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", pageNo)
                .queryParam("pageSize", pageSize);;

        url = builder.toUriString();
        Map<String, Object> responseBody =  getMethod(url, token);
        Page<DeviceBasicData> dataPage = new Page<>(pageNo, pageSize);
        if(responseBody.get("data")==null){
            log.warn("getDeviceListPage is empty====================");
            return dataPage;
        }
        List<DeviceBasicData> dataList = new ArrayList<>();
        List<Map> data = (List<Map>) responseBody.get("data");
        for(Map item: data){
            DeviceBasicData deviceBasicData = new DeviceBasicData();
            Object id = ((Map)item.get("id")).get("id");
            Object profiledId = ((Map)item.get("deviceProfileId")).get("id");
            Object name = item.get("name");
            Object type = item.get("type");
            Object label = item.get("label");
            deviceBasicData.setCoreId((String) id);
            deviceBasicData.setProfileId((String) profiledId);
            deviceBasicData.setName((String) name);
            deviceBasicData.setType((String) type);
            deviceBasicData.setLabel((String) label);
            dataList.add(deviceBasicData);
        }
        dataPage.setTotal((Long) responseBody.get("totalElements"));
        dataPage.setPages((Long) responseBody.get("totalPages"));
        dataPage.setRecords(dataList);
        return dataPage;
    }

    /**
     * 获取设备id数据
     * 通过设备名称获取
     *
     * @param token
     * @return
     */
    public List<DeviceBasicData> getDeviceList(String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(token)) {
            return null;
        }

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANT_DEVICES;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 1000);;

        url = builder.toUriString();
        Map<String, Object> responseBody =  getMethod(url, token);
        List<DeviceBasicData> dataList = new ArrayList<>();
        if(responseBody.get("data")==null){
            log.warn("getDeviceList is empty====================");
            return dataList;
        }
        List<Map> data = (List<Map>) responseBody.get("data");
        for(Map item: data){
            DeviceBasicData deviceBasicData = new DeviceBasicData();
            Object id = ((Map)item.get("id")).get("id");
            Object profiledId = ((Map)item.get("deviceProfileId")).get("id");
            Object name = item.get("name");
            Object type = item.get("type");
            Object label = item.get("label");
            deviceBasicData.setCoreId((String) id);
            deviceBasicData.setProfileId((String) profiledId);
            deviceBasicData.setName((String) name);
            deviceBasicData.setType((String) type);
            deviceBasicData.setLabel((String) label);
            dataList.add(deviceBasicData);
        }
        return dataList;
    }

    /**
     * 获取设备id数据
     * 通过设备名称获取
     *
     * @param deviceName
     * @param token
     * @return
     */
    public DeviceBasicData getDeviceByDeviceName(String deviceName, String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceName)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANT_DEVICES;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        builder.queryParam("deviceName", deviceName);

        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceByDeviceName 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            DeviceBasicData data = new DeviceBasicData();
            Object id = ((Map)responseBody.get("id")).get("id");
            Object profiledId = ((Map)responseBody.get("deviceProfileId")).get("id");
            Object name = responseBody.get("name");
            Object type = responseBody.get("type");
            Object label = responseBody.get("label");
            data.setCoreId((String) id);
            data.setProfileId((String) profiledId);
            data.setName((String) name);
            data.setType((String) type);
            data.setLabel((String) label);
            Object tenantId = ((Map)responseBody.get("tenantId")).get("id");
            data.setTenantId((String) tenantId);

            return data;

        } catch (HttpClientErrorException e) {
            if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                return null;
            }
            log.error("getDeviceByDeviceName, deviceName:{}", deviceName, e);
            throw e;
        }
    }

    /**
     * 删除设备
     *
     * @param deviceId
     * @return
     */
    public DeviceBasicData getDeviceById(String deviceId,String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.DELETE_DEVICE.replace("{deviceId}", deviceId);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceById 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            DeviceBasicData data = new DeviceBasicData();
            Map<String, Object> responseBody = responseEntity.getBody();
            Object id = ((Map)responseBody.get("id")).get("id");
            Object profiledId = ((Map)responseBody.get("deviceProfileId")).get("id");
            Object name = responseBody.get("name");
            Object type = responseBody.get("type");
            Object label = responseBody.get("label");
            data.setCoreId((String) id);
            data.setProfileId((String) profiledId);
            data.setName((String) name);
            data.setType((String) type);
            data.setLabel((String) label);

            return data;

        } catch (Exception e) {
            log.error("getDeviceById error:{}",e.getMessage());
            throw e;
        }
    }

    /**
     * 删除遥测数据
     *
     * @param deviceId
     * @param token
     * @return
     */
    public Map<String, List<DeviceTimeSeries>> deleteDataTelemetry(String deviceId, String token, String[] keys) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceId)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.DELETE_DEVICE_TELEMETRY.replace("{deviceId}", deviceId);
        // 构建请求参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        if (keys.length >0){
            String keysStr = String.join(",", keys);
            builder.queryParam("keys", keysStr);
            builder.queryParam("deleteAllDataForKeys", true);
        }


        url = builder.toUriString();

        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, List<DeviceTimeSeries>>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    new ParameterizedTypeReference<Map<String, List<DeviceTimeSeries>>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            Map<String, List<DeviceTimeSeries>> responseBody = responseEntity.getBody();

            log.warn("## deleteDataTelemetry url:{}, 执行结束： statusCode={}, 结果={}",url, statusCode, responseBody);
            return  responseBody;

        } catch (Exception e) {
            log.error("deleteDataTelemetry Exception ",e);
            throw e;
        }
    }

    /**
     * 删除属性数据
     *
     * @param deviceId
     * @param token
     * @return
     */
    public Map<String, List<DeviceTimeSeries>> deleteDataAttribute(String deviceId, String token, String[] keys) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceId)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.DELETE_DEVICE_ATTRIBUTES.replace("{deviceId}", deviceId);
        // 构建请求参数

        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        if (keys.length >0){
            String keysStr = String.join(",", keys);
            builder.queryParam("keys", keysStr);
        }


        url = builder.toUriString();

        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, List<DeviceTimeSeries>>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    new ParameterizedTypeReference<Map<String, List<DeviceTimeSeries>>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            Map<String, List<DeviceTimeSeries>> responseBody = responseEntity.getBody();

            log.info("## deleteDataAttribute url:{}, 执行结束： statusCode={}, 结果={}", url, statusCode, responseBody);
            return  responseBody;

        } catch (Exception e) {
            log.error("deleteDataAttribute Exception",e);
            throw e;
        }
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        //根据邮箱查询用户名和密码
        String token = null;
        String mail = "marketing@rexolar.com";
        String mailPassword = "Rex_sysadmin!@";
        try {
            Map map = authLogin(mail, mailPassword);
            if(map ==null){
                log.error("RexolarApiClient 获取token失败, mail1:{}, mailPassword:{}", mail, mailPassword);
                return null;
            }
            token = map.getOrDefault("token", "").toString();
            userTokenCache.put(mail, token);
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return token;
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getTenantToken(String tenantId) {
        String token = userTokenCache.getIfPresent(tenantId);
        if(StringUtils.isNotBlank(token)){
            return token;
        }
        //根据邮箱查询用户名和密码
        String sysToken = getToken();
        List<UserBasicData> users = getTenantUsers(tenantId, sysToken);
        if(CollectionUtils.isEmpty(users)){
            log.error("RexolarApiClient getTenantToken 获取租户下设备列表失败, tenantId:{}", tenantId);
            return null;
        }
        Map userToken =  getUserToken(users.get(0).getId(), sysToken);
        if(userToken ==null){
            log.error("RexolarApiClient getTenantToken 获取租户token, tenantId:{}", tenantId);
            return null;
        }
        token = userToken.getOrDefault("token", "").toString();
        userTokenCache.put(tenantId, token);
        return token;
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getTenantTokenByUser(String username, String password) {
        String token = userTokenCache.getIfPresent(username);
        if(StringUtils.isNotBlank(token)){
            return token;
        }
        Map map = authLogin(username, password);
        if(map ==null){
                log.error("RexolarApiClient 获取token失败, username:{}, mailPassword:{}", username, password);
            return null;
        }
        token = map.getOrDefault("token", "").toString();
        userTokenCache.put(username, token);
        return token;
    }

    /**
     * 获取租户下设备列表
     *
     * @param token
     * @param deviceId
     * @return
     */
    public List<DeviceBasicData> getToRelationsInfo(String token, String deviceId, String type) {
        List result = new ArrayList();
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceId)) {
            log.error("## getToRelationsInfo 参数不合规, token:{}, spaceInfoId:{}", token, deviceId);
            return result;
        }
        HttpHeaders headers = new HttpHeaders();
        DeviceBasicData data = new DeviceBasicData();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_RELATIONS_INFO;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        builder.queryParam("fromId", deviceId);
        builder.queryParam("fromType", type);

        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getToRelationsInfo 执行结束： url:{}, statusCode={}", url, statusCode);
                return result;
            }
            List<Map<String, Object>> responseBody = (List<Map<String, Object>>) responseEntity.getBody();
            for (int i = 0; i < responseBody.size(); i++) {
                DeviceBasicData deviceBasicData = new DeviceBasicData();
                Map jsonObject = responseBody.get(i);
                Map toMap = (Map) jsonObject.get("to");
                String gwId = (String) toMap.get("id");
                String name = (String) jsonObject.get("toName");
                deviceBasicData.setCoreId(gwId);
                deviceBasicData.setName(name);
                result.add(deviceBasicData);
            }
            return result;
        } catch (Exception e) {
            log.error("getToRelationsInfo Exception ",e);
            throw e;
        }
    }

    /**
     * 删除设备与网关的关联关系
     *
     * @param token
     * @param fromId
     * @param fromId
     * @param fromId
     * @return
     */
    public boolean deleteRelationsInfo(String token, String fromId, String fromType, String relationType, String toId, String toType) {
        List result = new ArrayList();
        //校验数据是否合规
        if (StringUtils.isBlank(token)
                || StringUtils.isBlank(fromId)
                || StringUtils.isBlank(fromType)
                || StringUtils.isBlank(relationType)
                || StringUtils.isBlank(toId)
                || StringUtils.isBlank(toType)
        ) {
            log.error("## deleteRelationsInfo 参数不合规, token:{}, fromId:{}, fromType:{}, relationType:{}, toId:{}, toType:{}", token, fromId, fromType, relationType, toId, toType);
            return false;
        }
        HttpHeaders headers = new HttpHeaders();
        DeviceBasicData data = new DeviceBasicData();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.API_RELATIONS;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        builder.queryParam("fromId", fromId);
        builder.queryParam("fromType", fromType);
        builder.queryParam("relationType", relationType);
        builder.queryParam("toId", toId);
        builder.queryParam("toType", toType);

        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    new ParameterizedTypeReference<>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## deleteRelationsInfo 执行结束： url:{}, statusCode={}", url, statusCode);
                return false;
            }
            return true;
        }catch (HttpClientErrorException ex){
            log.error("deleteRelationsInfo url:{} HttpClientErrorException ",url, ex);
            if(ex.getRawStatusCode() == 404){
                return true;
            }else {
                return false;
            }
        }catch (Exception e) {
            log.error("deleteRelationsInfo url:{} error",url, e);
            return false;
        }
    }

    /**
     * 添加关联关系
     *
     * @param token
     * @param fromId
     * @param fromId
     * @param fromId
     * @return
     */
    public boolean addRelationsInfo(String token, String fromId, String fromType, String relationType, String toId, String toType) {
        List result = new ArrayList();
        //校验数据是否合规
        if (StringUtils.isBlank(token)
                || StringUtils.isBlank(fromId)
                || StringUtils.isBlank(fromType)
                || StringUtils.isBlank(relationType)
                || StringUtils.isBlank(toId)
                || StringUtils.isBlank(toType)
        ) {
            log.error("## addRelationsInfo 参数不合规, token:{}, fromId:{}, fromType:{}, relationType:{}, toId:{}, toType:{}", token, fromId, fromType, relationType, toId, toType);
            return false;
        }
        HttpHeaders headers = new HttpHeaders();
        DeviceBasicData data = new DeviceBasicData();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);


        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.API_RELATIONS;
        Map<String, Object> requestBodyMap = new HashMap();

        Map<String, String> fromMap = new HashMap();
        fromMap.put("id", fromId);
        fromMap.put("entityType", fromType);
        Map<String, String> toMap = new HashMap();
        toMap.put("id", toId);
        toMap.put("entityType", toType);
        requestBodyMap.put("to", toMap);
        requestBodyMap.put("from", fromMap);
        requestBodyMap.put("type", relationType);
        requestBodyMap.put("typeGroup", "COMMON");
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        try {
            // 期望 JSON 响应
            ResponseEntity responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## addRelationsInfo 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }
            return true;
        }catch (HttpClientErrorException ex){
            log.error("addRelationsInfo HttpClientErrorException ",ex);
            if(ex.getRawStatusCode() == 404){
                return true;
            }else {
                return false;
            }
        }catch (Exception e) {
            log.error("addRelationsInfo error ",e);
            return false;
        }
    }

    /**
     * 获取租户下设备列表
     *
     * @param token
     * @param deviceId
     * @return
     */
    public List<DeviceBasicData> getFromRelationsInfo(String token, String deviceId) {
        List<DeviceBasicData> result = new ArrayList();
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(deviceId)) {
            log.error("## getFromRelationsInfo 参数不合规, token:{}, gwId:{}", token, deviceId);
            return result;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_RELATIONS_INFO;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        builder.queryParam("toId", deviceId);
        builder.queryParam("toType", "DEVICE");

        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getFromRelationsInfo 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return result;
            }
            List<Map<String, Object>> responseBody = (List<Map<String, Object>>) responseEntity.getBody();
            for (int i = 0; i < responseBody.size(); i++) {
                DeviceBasicData deviceBasicData = new DeviceBasicData();
                Map jsonObject = responseBody.get(i);
                if(!"Created".equals(jsonObject.get("type").toString())){
                    continue;
                }
                Map toMap = (Map) jsonObject.get("from");
                String gwId = (String) toMap.get("id");
                String name = (String) jsonObject.get("fromName");
                deviceBasicData.setCoreId(gwId);
                deviceBasicData.setName(name);
                result.add(deviceBasicData);
            }
            return result;
        } catch (Exception e) {
            log.error("getFromRelationsInfo error:{}",e);
            throw e;
        }
    }

    /**
     * 获取资产列表
     * 通过设备名称获取
     *
     * @param token
     * @return
     */
    public List<AssetResponse> getTenantAssetsInfo(String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANT_ASSETS_INFO;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 1000);
        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getTenantAssetsInfo 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            List<AssetResponse> list = new ArrayList<>();
            Map<String, Object> responseBody = responseEntity.getBody();
            if(responseBody!=null){
                List<Map> data = (List<Map>) responseBody.get("data");
                for (int i = 0; i < data.size(); i++){
                    if(data.get(i)==null){
                        continue;
                    }
                    if("TbServiceQueue".equals(data.get(i).get("assetProfileName"))){
                        continue;
                    }
                    AssetResponse assetBean = new AssetResponse();
                    Map asset = data.get(i);
                    Map idObj = (Map) asset.get("id");
                    assetBean.setSpaceId((String) idObj.get("id"));
                    assetBean.setSpaceName((String) asset.get("label"));
                    list.add(assetBean);
                }
            }
            return list;
        } catch (HttpClientErrorException e) {
            log.error("getTenantAssetsInfo ", e);
            throw e;
        }
    }

    /**
     *
     * @param token
     * @return
     */
    public Map<String, String> getDeviceProfiles(String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_PROFILES;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 1000);
        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceProfiles 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, String> deviceProfiles = new HashMap<>();
            Map<String, Object> responseBody = responseEntity.getBody();
            if(responseBody!=null){
                List<Map> dataList = (List<Map>) responseBody.get("data");
                for (int i = 0; i < dataList.size(); i++){
                    Map asset = dataList.get(i);
                    Map idMap = (Map) asset.get("id");
                    String profileId = (String) idMap.get("id");
                    String name = (String) asset.get("name");
                    deviceProfiles.put(profileId, name);
                }
            }
            return deviceProfiles;
        } catch (HttpClientErrorException e) {
            log.error("getDeviceProfiles ", e);
            throw e;
        }
    }

    /**
     *
     * @param token
     * @return
     */
    public Map<String, String> getDeviceProfilesImage(String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_PROFILES;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 1000);
        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceProfilesImage 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, String> deviceProfiles = new HashMap<>();
            Map<String, Object> responseBody = responseEntity.getBody();
            if(responseBody!=null){
                List<Map> dataList = (List<Map>) responseBody.get("data");
                for (int i = 0; i < dataList.size(); i++){
                    Map asset = dataList.get(i);
                    Map idMap = (Map) asset.get("id");
                    String profileId = (String) idMap.get("id");
                    String name = (String) asset.get("image");
                    deviceProfiles.put(profileId, name);
                }
            }
            return deviceProfiles;
        } catch (HttpClientErrorException e) {
            log.error("getDeviceProfilesImage ", e);
            throw e;
        }
    }

    /**
     *
     * @param token
     * @return
     */
    public List<Map<String, String>> getAlarms(String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_ALARMS;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 1000)
                .queryParam("sortProperty", "createdTime")
                .queryParam("sortOrder", "DESC")
                .queryParam("status", "ACTIVE_UNACK")
                ;
        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getAlarms 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            List<Map<String, String>> alarms = new ArrayList<>();
            Map<String, Object> responseBody = responseEntity.getBody();
            if(responseBody!=null){
                List<Map> dataList = (List<Map>) responseBody.get("data");
                for (int i = 0; i < dataList.size(); i++){
                    Map<String, String> alarmMap = new HashMap<>();
                    Map alarm = dataList.get(i);
                    Map idMap = (Map) alarm.get("id");
                    String alarmId = (String) idMap.get("id");
                    String originatorName = (String) alarm.get("originatorName");
                    String originatorLabel = (String) alarm.get("originatorLabel");
                    String status = (String) alarm.get("status");
                    String name = (String) alarm.get("name");
                    Long startTs = (Long) alarm.get("startTs");
                    String startTime = DateUtil.formatDateTime(DateUtil.date(startTs));
                    alarmMap.put("id", alarmId);
                    alarmMap.put("gwName", originatorName);
                    alarmMap.put("gwAlias", originatorLabel);
                    alarmMap.put("status", status);
                    alarmMap.put("name", name);
                    alarmMap.put("startTime", startTime);
                    alarms.add(alarmMap);
                }
            }
            return alarms;
        } catch (HttpClientErrorException e) {
            log.error("getAlarms ", e);
            throw e;
        }
    }

    /**
     *
     * @param token
     * @return
     */
    public List<TenantBasicData> getTenants(String token, String textSearch) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANTS;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParam("page", 0)
                .queryParam("pageSize", 1000)
                .queryParam("sortProperty", "createdTime")
                .queryParam("sortOrder", "DESC");
        if (StringUtils.isNotBlank(textSearch)){
            builder.queryParam("textSearch", textSearch);
        }
        url = builder.toUriString();
        List<TenantBasicData> tenantBasicDataList = new ArrayList<>();
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getTenants 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            if(responseBody!=null){
                List<Map> dataList = (List<Map>) responseBody.get("data");
                for (int i = 0; i < dataList.size(); i++){
                    TenantBasicData tenantBasicData = new TenantBasicData();
                    Map tenant = dataList.get(i);
                    Map idMap = (Map) tenant.get("id");
                    String id = (String) idMap.get("id");
                    tenantBasicData.setId(id);
                    tenantBasicData.setName((String) tenant.get("name"));
                    tenantBasicData.setCreatedTime((Long) responseBody.get("createdTime"));
                    tenantBasicData.setStatus(StatusEnum.ENABLE.getCode());
                    tenantBasicDataList.add(tenantBasicData);
                }
            }
            return tenantBasicDataList;
        } catch (HttpClientErrorException e) {
            log.error("getTenants ", e);
            return tenantBasicDataList;
        }
    }

    /**
     *
     * @param token
     * @return
     */
    public List<Map> getCustomersByEmail(String token, String email) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_CUSTOMERS;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 1000)
                .queryParam("sortProperty", "createdTime")
                .queryParam("sortOrder", "DESC")
                .queryParam("textSearch", email)
                ;
        url = builder.toUriString();
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getCustomersByEmail 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            List<Map> ids = new ArrayList<>();
            Map<String, Object> responseBody = responseEntity.getBody();
            if(responseBody!=null){
                List<Map> dataList = (List<Map>) responseBody.get("data");
                for (int i = 0; i < dataList.size(); i++){
                    Map<String, String> userMap = new HashMap<>();
                    Map User = dataList.get(i);
                    Map idMap = (Map) User.get("id");
                    String id = (String) idMap.get("id");
                    userMap.put("id", id);
                    userMap.put("email", User.get("email").toString());
                    Map tenantId = (Map) User.get("tenantId");
                    String tid = (String) tenantId.get("id");
                    userMap.put("tenantId", tid);
                    ids.add(userMap);
                }
            }
            return ids;
        } catch (HttpClientErrorException e) {
            log.error("getCustomersByEmail ", e);
            throw e;
        }
    }

    public Map<String, Object> getAuthUser(String token) {
        String url = customConfig.getHttpApi() + ApiConstant.AUTH_USER;
        return getMethod(url, token);
    }

    public AssetBasicData getAssetById(String spaceId, String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(spaceId)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_ASSET.replace("{spaceInfoId}", spaceId);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getAssetById 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            AssetBasicData data = new AssetBasicData();
            Map<String, Object> responseBody = responseEntity.getBody();
            Object name = responseBody.get("name");
            Object type = responseBody.get("type");
            Object label = responseBody.get("label");
            Map profileMap = (Map) responseBody.get("assetProfileId");
            String profileId = (String) profileMap.get("id");
            data.setProfileId(profileId);
            data.setName(name==null ? "" : name.toString());
            data.setType(type==null ? "" :type.toString());
            data.setLabel(label == null ? "" :label.toString());
            return data;

        } catch (Exception e) {
            log.error("getAssetById error:{}",e.getMessage());
            return null;
        }
    }

    public Map getUserToken(String userId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_USER_TOKEN.replace("{userId}", userId);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getUserToken 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            return responseBody;

        } catch (Exception e) {
            log.error("getUserToken error:{}",e.getMessage());
            throw e;
        }
    }

    public DeviceProfileBasicData getDeviceProfileById(String token, String profileId) {
        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_PROFILE_INFO.replace("{deviceProfileId}", profileId);
        Map<String, Object> data = getMethod(url, token);
        if(CollectionUtils.isNotEmpty(data)) {
            DeviceProfileBasicData deviceProfileBasicData = new DeviceProfileBasicData();
            deviceProfileBasicData.setProfileId(profileId);
            deviceProfileBasicData.setName(data.get("name").toString());
            deviceProfileBasicData.setImage(data.get("image")==null?"" : data.get("image").toString());
            deviceProfileBasicData.setDescription(data.get("description")==null?"" : data.get("description").toString());
            deviceProfileBasicData.setTransportType(data.get("transportType")==null?"" : data.get("transportType").toString());
            Map tenantIdMap = (Map)data.get("tenantId");
            deviceProfileBasicData.setTenantId(tenantIdMap.get("id").toString());
            return deviceProfileBasicData;
        }
        return null;
    }
    public String getTenantDefaultProfileId(String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANT_DEFAULT_PROFILE;
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getTenantDefaultProfileInfo 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);

        } catch (Exception e) {
            log.error("getTenantDefaultProfileInfo error:{}",e.getMessage());
            throw e;
        }
    }

    public String getAssetDefaultProfileId(String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_ASSET_DEFAULT_PROFILE;
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getAssetDefaultProfileId 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);

        } catch (Exception e) {
            log.error("getAssetDefaultProfileId error:{}",e.getMessage());
            throw e;
        }
    }

    /**
     * 动态创建租户
     *
     * @param token
     * @return
     */
    public String dynamicCreateTenant(String email, String profileId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("title", email);
        requestBodyMap.put("email", email);
        HashMap tenantProfileId = new HashMap();
        tenantProfileId.put("id", profileId);
        tenantProfileId.put("entityType", "TENANT_PROFILE");
        requestBodyMap.put("tenantProfileId", tenantProfileId);
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.CREATE_TENANT;
        log.info("dynamicCreateTenant Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## dynamicCreateTenant 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            log.warn("## dynamicCreateTenant 执行结束： statusCode={}, 结果={}", statusCode, responseBody);
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);
        } catch (Exception e) {
            log.error("dynamicCreateTenant error:{}",e.getMessage());
            throw e;
        }

    }

    /**
     * 动态创建客户
     *
     * @param token
     * @return
     */
    public String dynamicCreateCustomer(String email, String tenantId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("title", email);
        requestBodyMap.put("email", email);
        HashMap<String, String> tenantIdMap = new HashMap();
        tenantIdMap.put("id", tenantId);
        tenantIdMap.put("entityType", "TENANT");
        requestBodyMap.put("tenantId", tenantIdMap);
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.CREATE_CUSTOMER;
        log.info("dynamicCreateCustomer Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## dynamicCreateCustomer 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            log.warn("## dynamicCreateCustomer 执行结束： statusCode={}, 结果={}", statusCode, responseBody);
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);
        } catch (Exception e) {
            log.error("dynamicCreateCustomer error:{}",e.getMessage());
            throw e;
        }

    }

    public String createCustomUser(String username, String tenantId, String customerId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("authority", Constants.CUSTOMER_USER);
        requestBodyMap.put("email", username);
        HashMap<String, String> tenantProfileId = new HashMap();
        tenantProfileId.put("id", tenantId);
        tenantProfileId.put("entityType", "TENANT");
        requestBodyMap.put("tenantId", tenantProfileId);
        if(StringUtils.isNotBlank(customerId)){
            HashMap<String, String> customerIdMap = new HashMap();
            customerIdMap.put("id", customerId);
            customerIdMap.put("entityType", "CUSTOMER");
            requestBodyMap.put("customerId", customerIdMap);
        }
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.CREATE_TENANT_USER;
        log.info("createUser Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## createUser 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            log.warn("## createUser 执行结束： statusCode={}, 结果={}", statusCode, responseBody);
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);
        } catch (Exception e) {
            log.error("createUser error:{}",e.getMessage());
            throw e;
        }
    }

    public boolean changePassword(String password, String newPassword, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("currentPassword", password);
        requestBodyMap.put("newPassword", newPassword);
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.CHANGE_PASSWORD;
        log.info("changePassword Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## changePassword 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            log.warn("## changePassword 执行结束： statusCode={}, 结果={}", statusCode, responseBody);
            return true;
        } catch (Exception e) {
            log.error("changePassword error:{}",e.getMessage());
            throw e;
        }
    }

    public String dynamicAddCategory(String token, CategoryAddRequest categoryAddRequest) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("name", categoryAddRequest.getCategoryName());
        requestBodyMap.put("description", categoryAddRequest.getCategoryDesc());
        Map<String, Object> profileDataMap = new HashMap<>();
        Map<String, String> configuration = new HashMap();
        configuration.put("type", "DEFAULT");
        Map<String, String> provisionConfiguration = new HashMap();
        provisionConfiguration.put("type", "DISABLED");
        Map<String, String> transportConfiguration = new HashMap();
        transportConfiguration.put("type", "DEFAULT");
        profileDataMap.put("configuration", configuration);
        profileDataMap.put("provisionConfiguration", provisionConfiguration);
        profileDataMap.put("transportConfiguration", transportConfiguration);
        requestBodyMap.put("profileData", profileDataMap);
        requestBodyMap.put("provisionType", "DISABLED");
        requestBodyMap.put("transportType", "DEFAULT");
        requestBodyMap.put("type", "DEFAULT");

        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.ADD_DEVICE_PROFIELE;
        log.info("dynamicAddCategory Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## dynamicAddCategory 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            log.warn("## dynamicAddCategory 执行结束： statusCode={}, 结果={}", statusCode, responseBody);
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);
        } catch (Exception e) {
            log.error("dynamicAddCategory error:{}",e.getMessage());
            throw e;
        }
    }

    public AssetBasicData getAssetByName(String name, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_ASSETS + "?assetName=" + name;;
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getAssetByName 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            AssetBasicData data = new AssetBasicData();
            Map<String, Object> responseBody = responseEntity.getBody();
            Object type = responseBody.get("type");
            Object label = responseBody.get("label");
            Map profileMap = (Map) responseBody.get("assetProfileId");
            String profileId = (String) profileMap.get("id");
            data.setProfileId(profileId);
            data.setName(name==null ? "" : name.toString());
            data.setType(type==null ? "" :type.toString());
            data.setLabel(label == null ? "" :label.toString());
            return data;

        } catch (Exception e) {
            if(e instanceof HttpClientErrorException && ((HttpClientErrorException) e).getStatusCode()==HttpStatus.NOT_FOUND){
                return null;
            }
            log.error("getAssetByName error:{}",e.getMessage());
            throw e;
        }
    }

    public String dynamicCreateAsset(String spaceName, String profileId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("name", spaceName);
        requestBodyMap.put("description", "");
        Map<String, Object> assetProfileIdMap = new HashMap<>();
        assetProfileIdMap.put("entityType", "ASSET_PROFILE");
        assetProfileIdMap.put("id", profileId);
        requestBodyMap.put("assetProfileId", assetProfileIdMap);
        Map<String, String> customerIdMap = new HashMap<>();
        customerIdMap.put("entityType", "CUSTOMER");
        customerIdMap.put("id", JwtUtils.getCustomerId(token));
        requestBodyMap.put("customerId", customerIdMap);
        requestBodyMap.put("type", "DEFAULT");

        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.ADD_ASSET;
        log.info("dynamicCreateAsset Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## dynamicCreateAsset 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            log.warn("## dynamicCreateAsset 执行结束： statusCode={}, 结果={}", statusCode, responseBody);
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);
        } catch (Exception e) {
            log.error("dynamicAddCategory error:{}",e.getMessage());
            throw e;
        }
    }

    public boolean bindCustomerToAsset(String assetId, String customerId, String tenantToken) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + tenantToken);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.BIND_CUSTOMER_TO_ASSET;
        url = url.replace("{customerId}", customerId).replace("{assetId}", assetId);
        log.info("bindCustomerToAsset Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## bindCustomerToAsset 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("bindCustomerToAsset error:{}",e.getMessage());
            throw e;
        }
    }

    public boolean addCustomerDevice(String coreId, String customerId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.ADD_CUSTOMER_DEVICE;
        url = url.replace("{customerId}", customerId).replace("{deviceId}", coreId);
        log.info("addCustomerDevice Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## addCustomerDevice 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("addCustomerDevice error:{}",e.getMessage());
            throw e;
        }
    }

    public boolean deleteCustomerDevice(String coreId, String customerId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.DELETE_CUSTOMER_DEVICE;
        url = url.replace("{deviceId}", coreId);
        log.info("deleteCustomerDevice Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## deleteCustomerDevice 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("deleteCustomerDevice error:{}",e.getMessage());
            throw e;
        }
    }

    public boolean deleteCustomer(String customerId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);
        // 构建请求体的 JSON 字符串
        HashMap<String, Object> requestBodyMap = new HashMap<>();
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.DELETE_CUSTOMER;
        url = url.replace("{customerId}", customerId);
        log.info("deleteCustomer Url: " + url);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## deleteCustomer 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("deleteCustomer error:{}",e.getMessage());
            throw e;
        }
    }

    public List<AssetBasicData> getCustomerAssets(String customerId, String token) {
        String url = customConfig.getHttpApi() + ApiConstant.GET_CUSTOMER_ASSET.replace("{customerId}", customerId);
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 100)
                .queryParam("sortProperty", "createdTime")
                .queryParam("sortOrder", "DESC");
        url = builder.toUriString();
        Map<String, Object> responseBody = getMethod(url,token);
        List<AssetBasicData> assets = new ArrayList<>();
        if(responseBody.get("data")!=null){
            List<Map> data = (List<Map>) responseBody.get("data");
            for(Map item: data){
                AssetBasicData assetBasicData = new AssetBasicData();
                Object name = item.get("name");
                Object type = item.get("type");
                Object label = item.get("label");
                Map profileMap = (Map) item.get("assetProfileId");
                String profileId = (String) profileMap.get("id");
                assetBasicData.setProfileId(profileId);
                assetBasicData.setName(name==null ? "" : name.toString());
                assetBasicData.setType(type==null ? "" :type.toString());
                assetBasicData.setLabel(label == null ? "" :label.toString());
                Map idMap = (Map) item.get("id");
                assetBasicData.setCoreId((String) idMap.get("id"));
                assets.add(assetBasicData);
            }
        }
        return assets;
    }
    public List<DeviceBasicData> getCustomerDevices(String customerId, String token) {
        String url = customConfig.getHttpApi() + ApiConstant.GET_CUSTOMER_DEVICES.replace("{customerId}", customerId);
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("page", 0)
                .queryParam("pageSize", 100)
                .queryParam("sortProperty", "createdTime")
                .queryParam("sortOrder", "DESC");
        url = builder.toUriString();
        Map<String, Object> responseBody = getMethod(url,token);
        List<DeviceBasicData> dataList = new ArrayList<>();
        if(responseBody.get("data")!=null){
            List<Map> data = (List<Map>) responseBody.get("data");
            for(Map item: data){
                DeviceBasicData deviceBasicData = new DeviceBasicData();
                Object id = ((Map)item.get("id")).get("id");
                Object profiledId = ((Map)item.get("deviceProfileId")).get("id");
                Object name = item.get("name");
                Object type = item.get("type");
                Object label = item.get("label");
                deviceBasicData.setCoreId((String) id);
                deviceBasicData.setProfileId((String) profiledId);
                deviceBasicData.setName((String) name);
                deviceBasicData.setType((String) type);
                deviceBasicData.setLabel((String) label);
                dataList.add(deviceBasicData);
            }
        }
        return dataList;
    }

    public Map<String, Object> getDeviceInfoById(String coreId, String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(coreId)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_INFO.replace("{deviceId}", coreId);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceInfoById 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            return responseBody;

        } catch (HttpClientErrorException e) {
            log.error("getDeviceInfoById, url:{}", url, e);
            if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                return null;
            }
            throw e;
        }
    }

    public Map<String, Object> getDeviceCredentialsById(String coreId, String token) {
        //校验数据是否合规
        if (StringUtils.isBlank(token) || StringUtils.isBlank(coreId)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_DEVICE_CREDENTIALS.replace("{deviceId}", coreId);
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getDeviceCredentialsById 执行结束： url:{}, statusCode={}", url, statusCode);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            return responseBody;

        } catch (HttpClientErrorException e) {
            log.error("getDeviceCredentialsById, url:{}", url, e);
            if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                return null;
            }
            throw e;
        }
    }


    public String updateDevice(Map<String, Object> device, String token) {
        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.ADD_UPDATE_DEVICE;
        String data = JSON.toJSONString(device);
        Map<String, Object> responseBody = postMethod(url, data, token);
        if (responseBody.get("id") != null) {
            Map idMap = (Map)responseBody.get("id");
            Object id = idMap.get("id");
            return String.valueOf(id);
        }else {
            return "";
        }
    }

    public TenantBasicData getTenantById(String tenantId, String token) {
        HttpHeaders headers = new HttpHeaders();

        headers.add("Content-Type", "application/json");
        headers.add("accept", "application/json");
        headers.add("X-Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        //构建请求链接
        String url = customConfig.getHttpApi() + ApiConstant.GET_TENANT_INFO.replace("{tenantId}", tenantId);
        List<TenantBasicData> tenantBasicDataList = new ArrayList<>();
        try {
            // 期望 JSON 响应
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<Map<String,Object>>() {
                    }
            );

            HttpStatus statusCode = responseEntity.getStatusCode();
            if (!statusCode.is2xxSuccessful()) {
                log.error("## getTenantById 执行结束： url:{}, statusCode={}, 结果={}", url, statusCode, responseEntity);
                return null;
            }
            Map<String, Object> responseBody = responseEntity.getBody();
            if(responseBody!=null){
                TenantBasicData tenantBasicData = new TenantBasicData();
                Map idMap = (Map) responseBody.get("id");
                String id = (String) idMap.get("id");
                tenantBasicData.setId(id);
                tenantBasicData.setName((String) responseBody.get("name"));
                tenantBasicData.setCreatedTime((Long) responseBody.get("createdTime"));
                tenantBasicData.setStatus(StatusEnum.ENABLE.getCode());
                return tenantBasicData;
            }
        } catch (HttpClientErrorException e) {
            log.error("getTenantById ", e);
        }
        return null;
    }
}
